﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Workflow;
using System.Threading;
using System.Linq.Expressions;
using System.Reflection;

namespace WorkflowStarter
{
    public partial class WorkflowStarterForm : Form
    {
        private static readonly uint RowLimit = 20000;

        public delegate void LogHandler(string itemTitle, string workflow, string message);
        public delegate void ButtonStatusHandler(bool enabled);

        private bool idle = true;
        private bool requestAbort = false;

        private SPSite site = null;

        public WorkflowStarterForm()
        {
            InitializeComponent();
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            base.OnClosing(e);
            if (this.site != null)
            {
                this.site.Dispose();
            }
        }

        private void LoadSiteCollectionButton_Click(object sender, EventArgs e)
        {
            this.SiteComboBox.Items.Clear();
            if (string.IsNullOrEmpty(this.SiteCollectionTextBox.Text))
            {
                return;
            }

            try
            {
                if (this.site != null)
                {
                    this.site.Dispose();
                }

                this.site = new SPSite(this.SiteCollectionTextBox.Text);
                foreach (SPWeb web in site.AllWebs)
                {
                    using (web)
                    {
                        this.SiteComboBox.Items.Add(new ComboBoxItem(web.Title) { Id = web.ID });
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void SiteComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.ListComboBox.Items.Clear();
            if (this.SiteComboBox.SelectedIndex == -1)
            {
                return;
            }

            ComboBoxItem comboBoxItemSite = this.SiteComboBox.SelectedItem as ComboBoxItem;
            using (SPWeb web = site.OpenWeb(comboBoxItemSite.Id))
            {
                foreach (SPList list in web.Lists)
                {
                    this.ListComboBox.Items.Add(new ComboBoxItem(list.Title) { Id = list.ID });
                }
            }
        }

        private void ListComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.ViewComboBox.Items.Clear();
            this.WorkflowComboBox.Items.Clear();
            if (this.ListComboBox.SelectedIndex == -1)
            {
                return;
            }

            ComboBoxItem comboBoxItemSite = this.SiteComboBox.SelectedItem as ComboBoxItem;
            using (SPWeb web = site.OpenWeb(comboBoxItemSite.Id))
            {
                ComboBoxItem comboBoxItemList = this.ListComboBox.SelectedItem as ComboBoxItem;
                SPList list = web.Lists[comboBoxItemList.Id];
                foreach (SPView view in list.Views)
                {
                    this.ViewComboBox.Items.Add(new ComboBoxItem(view.Title) { Id = view.ID });
                }

                foreach (SPWorkflowAssociation association in list.WorkflowAssociations)
                {
                    this.WorkflowComboBox.Items.Add(new ComboBoxItem(association.Name) { Id = association.Id });
                }
            }
        }

        private void EixtButton_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void TerminateButton_Click(object sender, EventArgs e)
        {
            if (!this.idle)
            {
                this.requestAbort = true;
                this.TerminateButton.Text = "Aborting";
                this.TerminateButton.Enabled = false;
                this.StartButton.Enabled = false;
                return;
            }

            if (string.IsNullOrEmpty(this.SiteCollectionTextBox.Text)
                 || this.SiteComboBox.SelectedIndex == -1
                 || this.ListComboBox.SelectedIndex == -1
                 || this.WorkflowComboBox.SelectedIndex == -1)
            {
                return;
            }

            ComboBoxItem comboBoxItemSite = this.SiteComboBox.SelectedItem as ComboBoxItem;
            ComboBoxItem comboBoxItemList = this.ListComboBox.SelectedItem as ComboBoxItem;
            ComboBoxItem comboBoxItemView = this.ViewComboBox.SelectedItem as ComboBoxItem;
            ComboBoxItem comboBoxItemWorkflow = this.WorkflowComboBox.SelectedItem as ComboBoxItem;
            this.TerminateButton.Text = "Abort";
            this.idle = false;
            try
            {
                Thread thread = new Thread(new ParameterizedThreadStart(Process));
                thread.Start(new WorkflowOperationParameter()
                {
                    SiteId = this.site.ID,
                    WebId = comboBoxItemSite.Id,
                    ListId = comboBoxItemList.Id,
                    ViewId = comboBoxItemView == null ? Guid.Empty : comboBoxItemView.Id,
                    WorkflowAssociationId = comboBoxItemWorkflow.Id,
                    ForceRestart = this.ForceRestartCheckBox.Checked,
                    Operation = WorkflowOperation.Terminate
                });
            }
            catch (Exception ex)
            {
                this.TerminateButton.Text = "Terminate";
                this.TerminateButton.Enabled = true;
                this.StartButton.Enabled = true;
                this.idle = true;
                MessageBox.Show(ex.ToString());
            }
        }

        private void StartButton_Click(object sender, EventArgs e)
        {
            if (!this.idle)
            {
                this.requestAbort = true;
                this.StartButton.Text = "Aborting";
                this.StartButton.Enabled = false;
                return;
            }

            if (string.IsNullOrEmpty(this.SiteCollectionTextBox.Text)
                || this.SiteComboBox.SelectedIndex == -1
                || this.ListComboBox.SelectedIndex == -1
                || this.WorkflowComboBox.SelectedIndex == -1)
            {
                return;
            }

            ComboBoxItem comboBoxItemSite = this.SiteComboBox.SelectedItem as ComboBoxItem;
            ComboBoxItem comboBoxItemList = this.ListComboBox.SelectedItem as ComboBoxItem;
            ComboBoxItem comboBoxItemView = this.ViewComboBox.SelectedItem as ComboBoxItem;
            ComboBoxItem comboBoxItemWorkflow = this.WorkflowComboBox.SelectedItem as ComboBoxItem;
            this.StartButton.Text = "Abort";
            this.idle = false;
            try
            {
                Thread thread = new Thread(new ParameterizedThreadStart(Process));
                thread.Start(new WorkflowOperationParameter()
                {
                    SiteId = this.site.ID,
                    WebId = comboBoxItemSite.Id,
                    ListId = comboBoxItemList.Id,
                    ViewId = comboBoxItemView == null ? Guid.Empty : comboBoxItemView.Id,
                    WorkflowAssociationId = comboBoxItemWorkflow.Id,
                    ForceRestart = this.ForceRestartCheckBox.Checked,
                    Operation = WorkflowOperation.Start
                });
            }
            catch (Exception ex)
            {
                this.StartButton.Text = "Start";
                this.StartButton.Enabled = true;
                this.idle = true;
                MessageBox.Show(ex.ToString());
            }
        }

        private SPListItemCollection GetItems(SPList list, SPView view)
        {
            SPListItemCollection items = null;
            if (view != null)
            {
                SPQuery query = new SPQuery(view);
                query.RowLimit = RowLimit;
                items = list.GetItems(query);
            }
            else
            {
                items = list.Items;
            }

            return items;
        }

        private void EnableButton(bool enabled)
        {
            this.StartButton.Enabled = enabled;
            this.StartButton.Text = enabled ? "Start" : "Aborting";
            this.TerminateButton.Enabled = enabled;
            this.TerminateButton.Text = enabled ? "Terminate" : "Aborting";
        }

        private void Process(object param)
        {
            WorkflowOperationParameter parameter = param as WorkflowOperationParameter;
            using (SPSite site = new SPSite(parameter.SiteId))
            {
                using (SPWeb web = site.OpenWeb(parameter.WebId))
                {
                    SPList list = web.Lists[parameter.ListId];
                    SPView view = (parameter.ViewId == Guid.Empty) ? null : list.Views[parameter.ViewId];
                    SPWorkflowAssociation association = list.WorkflowAssociations[parameter.WorkflowAssociationId];
                    SPListItemCollection items = this.GetItems(list, view);
                    foreach (SPListItem item in items)
                    {
                        if (this.requestAbort)
                        {
                            this.requestAbort = false;
                            break;
                        }

                        Thread.Sleep(1000);

                        try
                        {
                            switch (parameter.Operation)
                            {
                                case WorkflowOperation.Start:
                                    this.StartWorkflow(item, association, parameter.ForceRestart);
                                    break;

                                case WorkflowOperation.Terminate:
                                    this.TerminateWorkflow(item, association);
                                    break;

                                default:
                                    break;

                            }

                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString());
                        }
                    }
                }
            }

            this.idle = true;
            this.StartButton.Invoke(new ButtonStatusHandler(this.EnableButton), true);
        }

        private string TryGetItemIdentifier(SPListItem item)
        {
            string identifier = string.Empty;
            try
            {
                SPField titleField = item.Fields.GetField("Title");
                if (item.File != null)
                {
                    identifier = item.Name;
                }
                else if (titleField.Hidden)
                {
                    identifier = titleField.GetFieldValueAsText(item[titleField.Id]);
                }
                else
                {
                    identifier = item.Title;
                }
            }
            catch (ArgumentException) // This will happen if the Title is not exist in the selected view.
            {
                identifier = item.ID.ToString();
            }

            return identifier;
        }

        private void TerminateWorkflow(SPListItem item, SPWorkflowAssociation association)
        {
            SPWorkflowManager manager = item.ParentList.ParentWeb.Site.WorkflowManager;
            SPWorkflow runningWorkflow = item.Workflows.GetById(association.Id);
            string message = string.Empty;
            try
            {
                if (runningWorkflow == null)
                {
                    message = "Skip (No Instance)";
                }
                else
                {
                    switch (runningWorkflow.InternalState)
                    {
                        case SPWorkflowState.Cancelled:
                        case SPWorkflowState.Completed:
                        case SPWorkflowState.Terminated:
                            message = string.Format("Skip (Internal State: {0})", runningWorkflow.InternalState.ToString());
                            break;

                        default:
                            SPWorkflowManager.CancelWorkflow(runningWorkflow);
                            message = "Terminated";
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }

            this.LogListView.Invoke(new LogHandler(this.Log), TryGetItemIdentifier(item), association.Name, message);
        }

        private void StartWorkflow(SPListItem item, SPWorkflowAssociation association, bool forceRestart)
        {
            SPWorkflowManager manager = item.ParentList.ParentWeb.Site.WorkflowManager;
            SPWorkflow runningWorkflow = item.Workflows.GetById(association.Id);
            string message = string.Empty;
            try
            {
                if (runningWorkflow == null)
                {
                    manager.StartWorkflow(item, association, string.Empty, true);
                    message = "Started";
                }
                else
                {
                    if (forceRestart)
                    {
                        manager.RemoveWorkflowFromListItem(runningWorkflow);
                        manager.StartWorkflow(item, association, "", true);
                        message = "Started";
                    }
                    else
                    {
                        message = string.Format("Skip (Internal State: {0})", runningWorkflow.InternalState.ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }

            this.LogListView.Invoke(new LogHandler(this.Log), TryGetItemIdentifier(item), association.Name, message);
        }

        private void Log(string itemTitle, string workflow, string message)
        {
            this.LogListView.Items.Insert(0, new ListViewItem(new string[] { itemTitle, workflow, message }));
        }

        private void ClearLogButton_Click(object sender, EventArgs e)
        {
            this.LogListView.Items.Clear();
        }
    }

    public enum WorkflowOperation
    {
        Start = 1,
        Terminate = 2
    }

    public class WorkflowOperationParameter
    {
        public Guid SiteId
        {
            get;
            set;
        }

        public Guid WebId
        {
            get;
            set;
        }

        public Guid ListId
        {
            get;
            set;
        }

        public Guid ViewId
        {
            get;
            set;
        }

        public Guid WorkflowAssociationId
        {
            get;
            set;
        }

        public bool ForceRestart
        {
            get;
            set;
        }

        public WorkflowOperation Operation
        {
            get;
            set;
        }
    }
}
